package com.raven.play.hello;

import akka.actor.typed.ActorRef;
import akka.actor.typed.Behavior;
import akka.actor.typed.javadsl.AbstractBehavior;
import akka.actor.typed.javadsl.ActorContext;
import akka.actor.typed.javadsl.Behaviors;
import akka.actor.typed.javadsl.Receive;
import com.raven.play.hello.msg.Greet;
import com.raven.play.hello.msg.Greeted;
import com.raven.play.hello.msg.SayHello;

public class HelloWorldMain extends AbstractBehavior<SayHello> {

  public static Behavior<SayHello> create() {
    return Behaviors.setup(HelloWorldMain::new);
  }

  private final ActorRef<Greet> greeter;

  /**
   * 通过 context.spawn 来创建 actor
   * @param context
   */
  private HelloWorldMain(ActorContext<SayHello> context) {
    super(context);
    greeter = context.spawn(HelloWorld.create(), "greeter");
  }

  @Override
  public Receive<SayHello> createReceive() {
    return newReceiveBuilder().onMessage(SayHello.class, this::onStart).build();
  }

  /**
   * Behavior 方法最终返回 this
   * @param command
   * @return
   */
  private Behavior<SayHello> onStart(SayHello command) {
    ActorRef<Greeted> replyTo =
        getContext().spawn(HelloWorldBot.create(3), command.name());
    greeter.tell(new Greet(command.name(), replyTo));
    return this;
  }
}